package com.xuesi.demoadmin.exception.handler;

import com.xuesi.demoadmin.entity.R;
import com.xuesi.demoadmin.utils.ThrowableUtil;
import org.springframework.validation.FieldError;
import org.springframework.validation.ObjectError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.ControllerAdvice;

import lombok.extern.slf4j.Slf4j;

@Slf4j
@ControllerAdvice
public class GlobalExceptionHandler {

    /**
     * 处理所有不可知的异常
     */
    @ExceptionHandler(Throwable.class)
    public R<Object> handleException(Throwable e) {
        // log.error(ThrowableUtil.getStackTrace(e));
        return new R<Object>(500, e.getMessage());
    }

    // /**
    // * 处理自定义异常
    // */
    // @ExceptionHandler(value = BadRequestException.class)
    // public ResponseEntity<ApiError> badRequestException(BadRequestException e) {
    // // 打印堆栈信息
    // log.error(ThrowableUtil.getStackTrace(e));
    // return buildResponseEntity(ApiError.error(e.getStatus(), e.getMessage()));
    // }

    /**
     * 处理所有接口数据验证异常
     */
    @ResponseBody
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public R<Object> handleMethodArgumentNotValidException(MethodArgumentNotValidException e) {
        // 打印堆栈信息
        // log.error(ThrowableUtil.getStackTrace(e));
        ObjectError objectError = e.getBindingResult().getAllErrors().get(0);
        String message = objectError.getDefaultMessage();
        return new R<Object>(500, message);
    }
}